package com.bs.process.project.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bs.common.annotation.Log;
import com.bs.common.config.Global;
import com.bs.common.enums.BusinessType;
import com.bs.process.project.domain.SysProject;
import com.bs.process.project.domain.SysProjectFile;
import com.bs.process.project.domain.SysProjectFileType;
import com.bs.process.project.service.ISysProjectFileService;
import com.bs.process.project.service.ISysProjectFileTypeService;
import com.bs.process.project.service.ISysProjectService;

import sun.misc.BASE64Encoder;

import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.utils.poi.ExcelUtil;
import com.bs.framework.util.ShiroUtils;

/**
 * 项目文件Controller
 *
 * @author Xianlu Tech
 * @date 2020-06-13
 */
@Controller
@RequestMapping("/process/projectfile")
public class SysProjectFileController extends BaseController {
	private String prefix = "process/project/file";

	@Autowired
	private ISysProjectFileService sysProjectFileService;
	@Autowired
	private ISysProjectFileTypeService sysProjectFileTypeService;

	@Autowired
	private ISysProjectService sysProjectService;

	@RequiresPermissions("process:file:view")
	@GetMapping()
	public String file() {
		return prefix + "/file";
	}

	/**
	 * 查询项目文件列表
	 */
	@RequiresPermissions("process:file:list")
	@PostMapping("/list")
	@ResponseBody
	public List<SysProjectFile> list(SysProjectFile sysProjectFile) {
		List<SysProjectFile> list = sysProjectFileService.selectSysProjectFileList(sysProjectFile);
		return list;
	}

	/**
	 * 导出项目文件列表
	 */
	@RequiresPermissions("process:file:export")
	@PostMapping("/export")
	@ResponseBody
	public AjaxResult export(SysProjectFile sysProjectFile) {
		List<SysProjectFile> list = sysProjectFileService.selectSysProjectFileList(sysProjectFile);
		ExcelUtil<SysProjectFile> util = new ExcelUtil<SysProjectFile>(SysProjectFile.class);
		return util.exportExcel(list, "file");
	}

	/**
	 * 新增项目文件
	 */
	@GetMapping("/add/{id}")
	public String add(@PathVariable("id") Long id, ModelMap mmap) {
		SysProjectFile sysProjectFile = sysProjectFileService.selectSysProjectFileById(id);
		SysProject project = sysProjectService.selectSysProjectById(sysProjectFile.getProjectId());
		mmap.put("sysProject", project);
		mmap.put("sysProjectFile", sysProjectFile);
		return prefix + "/add";
	}

	/**
	 * 查看详情，预览
	 */
	@GetMapping("/filedetail/{id}")
	public String filedetail(@PathVariable("id") Long id, ModelMap mmap) {
		SysProjectFile sysProjectFile = sysProjectFileService.selectSysProjectFileById(id);
		if (sysProjectFile != null) {
			sysProjectFile.setImgData(imageToBase64(sysProjectFile.getUrl()));
		}
		mmap.put("sysProjectFile", sysProjectFile);
		return prefix + "/filedetail";
	}

	/**
	 * 新增保存项目文件
	 */
	@RequiresPermissions("process:file:add")
	@Log(title = "项目文件", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(SysProjectFile sysProjectFile, MultipartFile[] attachment) {
		return toAjax(sysProjectFileService.insertSysProjectFile(sysProjectFile, attachment));
	}

	/**
	 * 修改项目文件
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap mmap) {
		SysProjectFile sysProjectFile = sysProjectFileService.selectSysProjectFileById(id);
		mmap.put("sysProjectFile", sysProjectFile);
		return prefix + "/edit";
	}

	/**
	 * 修改保存项目文件
	 */
	@RequiresPermissions("process:file:edit")
	@Log(title = "项目文件", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(SysProjectFile sysProjectFile) {
		return toAjax(sysProjectFileService.updateSysProjectFile(sysProjectFile));
	}

	/**
	 * 下载项目文件
	 */
	@GetMapping("/downloadFile/{id}")
	public void downloadFile(@PathVariable("id") Long id, HttpServletResponse resp) {
		SysProjectFile sysProjectFile = sysProjectFileService.selectSysProjectFileById(id);
		if (sysProjectFile == null)
			return;
		String filename = sysProjectFile.getFileName();
		// 设置信息给客户端不解析
		String type = new MimetypesFileTypeMap().getContentType(filename);
		resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
		resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
		resp.setHeader("Content-type", type);
		Path path = Paths.get(Global.getProfile()+sysProjectFile.getUrl());
		try {
			Files.copy(path, resp.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除项目文件
	 */
	@RequiresPermissions("process:file:remove")
	@Log(title = "项目文件", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	public AjaxResult remove(String ids) {
		return toAjax(sysProjectFileService.deleteSysProjectFileByIds(ids));
	}

	@GetMapping("/remove/{id}")
	@ResponseBody
	public AjaxResult removeById(@PathVariable("id") Long id) {
		if (sysProjectFileService.selectCountSysProjectFileByParentId(id) > 0) {
			return AjaxResult.warn("存在子菜单,不允许删除");
		}
		ShiroUtils.clearCachedAuthorizationInfo();
		return toAjax(sysProjectFileService.deleteSysProjectFileById(id));
	}

	public String imageToBase64(String imgPath) {
		try {
			InputStream in = new FileInputStream(imgPath);
			byte[] data = new byte[in.available()];
			in.read(data);
			in.close();
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
